package com.crm.miaohe.service;

import com.crm.miaohe.controller.report.response.OrderReportMonth;
import com.crm.miaohe.mapper.TblOrderMapper;
import com.crm.miaohe.model.TblOrder;
import com.crm.miaohe.model.TblOrderExample;
import com.crm.miaohe.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("monthOrderReportService")
public class OrderMonthReportService implements OrderReportService<OrderReportMonth> {

    private TblOrderMapper tblOrderMapper;

    public OrderMonthReportService(TblOrderMapper tblOrderMapper) {
        this.tblOrderMapper = tblOrderMapper;
    }

    @Override
    public OrderReportMonth orderReport() {
        LocalDate startOfCurrentMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
        int totalDays = startOfCurrentMonth.lengthOfMonth();
        OrderReportMonth history = new OrderReportMonth(startOfCurrentMonth.getMonthValue(), totalDays);
        TblOrderExample orderExample = new TblOrderExample();
        orderExample.createCriteria().andCreateTimeBetween(startOfCurrentMonth.atStartOfDay(), startOfCurrentMonth.with(TemporalAdjusters.firstDayOfNextMonth()).atStartOfDay().plusDays(1).minusSeconds(1)).andStatusEqualTo(1);
        List<Map.Entry<LocalDate, List<TblOrder>>> entries = tblOrderMapper.selectByExample(orderExample)
                .stream().collect(Collectors.groupingBy(tblOrder -> tblOrder.getCreateTime().toLocalDate()))
                .entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());

        int dayOfMonth = 0, index = 0, size = entries.size();
        while (dayOfMonth <= totalDays && index < size) {
            LocalDate day = startOfCurrentMonth.plusDays(dayOfMonth);
            Map.Entry<LocalDate, List<TblOrder>> entry = entries.get(index);
            if (day.equals(entry.getKey())) {
                history.getAlertMonthHistory().add(BigInteger.valueOf(entry.getValue().size()));
                index++;
            } else {
                history.getAlertMonthHistory().add(BigInteger.ZERO);
            }
            dayOfMonth++;
        }
        List<BigInteger> historyData = history.getAlertMonthHistory();
        List<String> historyDay = history.getAlertMonthDay();
        int month = startOfCurrentMonth.getMonthValue();
        int day = 1;
        while (historyData.size() <= totalDays) {
            historyData.add(BigInteger.ZERO);
        }
        while (day <= totalDays) {
            historyDay.add(StringUtils.padRight(String.valueOf(month), 2, '0').concat("/").concat(StringUtils.padRight(String.valueOf(day), 2, '0')));
            day++;
        }
        return history;
    }
}
